package com.hk.core.autoconfigure.weixin.miniapp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;


/**
 * wechat miniapp configuration
 *
 * @author Kevin
 */
@AutoConfiguration
@ConditionalOnClass(WxMaService.class)
@ConditionalOnProperty(prefix = "wx.mini", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(WeiXinMiniappProperties.class)
public class WeiXinMiniappConfiguration {

    private final WeiXinMiniappProperties properties;

    public WeiXinMiniappConfiguration(WeiXinMiniappProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public WxMaConfig wxMaConfig() {
        var configStorage = new WxMaDefaultConfigImpl();
        configStorage.setAppid(properties.getAppId());
        configStorage.setSecret(properties.getSecret());
        configStorage.setToken(properties.getToken());
        configStorage.setAesKey(properties.getAesKey());
        configStorage.setMsgDataFormat(properties.getMsgDataFormat());
        return configStorage;
    }

    @Bean
    public WxMaService wxMaService(WxMaConfig wxMaConfig) {
        var wxMpService = new WxMaServiceImpl();
        wxMpService.setWxMaConfig(wxMaConfig);
        return wxMpService;
    }
}
